package by.grsu.pereverzev.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import by.grsu.pereverzev.entity.Flight;
import by.grsu.pereverzev.table.FlightTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class FlightDao extends AbstractDao<FlightTable, Flight> {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = -7616398199418924442L;

	public FlightDao(final String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public Long saveNew(final Flight newFlight) {
		// set ID
		Long nextId = getNextId();
		newFlight.setId(nextId);
		// get existing data
		final FlightTable flightTable = deserializeFromXml();
		// add new row
		flightTable.getRows().add(newFlight);
		// save data
		serializeToXml(flightTable);
		return nextId;
	}

	@Override
	public void update(final Flight entity) {
		// get existing data
		final FlightTable flightTable = deserializeFromXml();
		// find by ID
		for (final Flight row : flightTable.getRows()) {
			if (row.getId().equals(entity.getId())) {
				// found!!!
				// copy data
				row.setId(entity.getId());
				row.setDestStation(entity.getDestStation());
				row.setDateOfDeparture(entity.getDateOfDeparture());
				row.setCost(entity.getCost());
				break;
			}
		}
		// save updated table
		serializeToXml(flightTable);
	}

	@Override
	public Flight get(final Serializable id) {
		// get existing data
		final FlightTable flightTable = deserializeFromXml();
		// find by ID
		for (final Flight row : flightTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}
	
	@Override
	public List<Flight> getAll() {
		// get existing data
		final FlightTable flightTable = deserializeFromXml();
		return flightTable.getRows();
	}
	
	@Override
	public void delete(final Serializable id) {
		// get existing data
		final FlightTable flightTable = deserializeFromXml();
		// find by ID
		Flight toBeDeleted = null;
		for (final Flight row : flightTable.getRows()) {
			if (row.getId().equals(id)) {
				// found!!!
				toBeDeleted = row;
				break;
			}
		}
		// remove from list
		flightTable.getRows().remove(toBeDeleted);
		// save updated table
		serializeToXml(flightTable);
	}

	public List<Flight> getFlightsInDayToStation(Date date, String station) {
		List<Flight> result = new ArrayList<Flight>();
		List<Flight> allFlights = getAll();
		for (Flight flight : allFlights) {
			if (station.equals(flight.getDestStation()) &&
					flight.getDateOfDeparture().getMonth() == date.getMonth() &&
							flight.getDateOfDeparture().getDate() == date.getDate()) {
						result.add(flight);
			}
		}
		return result;
	}
	
	@Override
	protected Class<FlightTable> getTableClass() {
		return FlightTable.class;
	}

}
